package com.example.ceshi;

import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description : 测试-通过验证码获取信息
 *
 * @ClassName : TestController
 * @Author : xm
 * @Date: 2024/08/15
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/kaptcha")
    @CrossOrigin
    public Map getValid(HttpServletResponse response) throws IOException {

        Map map = new HashMap<>();
        String url = " https://二维码地址";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");
        con.setInstanceFollowRedirects(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setUseCaches(false);


        // 获取所有的响应头字段
        String cookieVal = con.getHeaderField("Set-Cookie");
        List<HttpCookie> cookies = HttpCookie.parse(cookieVal);

        // 输出cookie
        String cookieValue = "";
        String cookieName ="";
        String cookieCode = "";
        for (HttpCookie cookie : cookies) {
            System.out.println("Cookie: " + cookie.getName() + " = " + cookie.getValue());
            cookieValue = cookie.getName() + " = " + cookie.getValue();
            cookieName = cookie.getName();
            cookieCode = cookie.getValue();
        }


        String encoder = "data:image/jpg;base64,"; //定义图片类型，方便前端直接使用
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        InputStream is = con.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1){
            data.write(bytes,0,len);
        }
        is.close();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        encoder = encoder +  base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();//这里去掉结果里面的"\r\n"，也可以不去，但是不去的话需要使用的时候还是要去掉，所以为了方便就先去掉再存
        //System.out.println(encoder);


        Cookie c1 = new Cookie(cookieName, cookieCode);
        // 3.设置存活时间,1周 7天
        c1.setMaxAge(60*60*24*7);
        // 4.向浏览器发送cookie
        response.addCookie(c1);

        //获取流
        InputStream inputStream = con.getInputStream();
        //读取图片
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        if (bufferedImage!=null){
            //获取图片格式
            String format = url.substring(url.lastIndexOf(".") + 1);
            //打印图片
            ImageIO.write(bufferedImage,format,response.getOutputStream());// 将文件流放入response中
        }

        con.disconnect();
        map.put("cookies",cookieValue);
        map.put("img",encoder);
        return map;
    }



    @PostMapping("/getdata")
    @CrossOrigin
    public Map getdata(@RequestBody test test) throws IOException {
        Map map = new HashMap<>();
        String urlString = "https://最终接口请求地址"; // 替换为你需要访问的URL
        String cookieValue = test.getCookie();
        URL url2 = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        // 设置请求属性，包括Cookie
        connection.setRequestProperty("Cookie", cookieValue);

        // 发送post请求
        connection.setRequestMethod("POST");
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        String content = "此处写参数";
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(content.getBytes());
        outputStream.flush();
        outputStream.close();

        System.out.println(content);
        StringBuilder response = new StringBuilder();
        // 接收响应
        int responseCode = connection.getResponseCode();
        String newUrl = null;

        if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
            newUrl = connection.getHeaderField("Location");
            System.out.println("Redirected to: " + newUrl);
        } else {
            System.out.println("No redirection");
        }
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;


            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            in.close();

            // 打印结果
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }

        connection.disconnect();
        //// 关闭连接
        //con.disconnect();
        map.put("result",newUrl);
        return map;
    }

}